package com.example.demo.myBlockingQueue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyArrayBlockingQueue {


    private final Object[] arr ;

    private final ReentrantLock lock;

    private final Condition notEmpty;

    private final Condition notFull;

    private final int size;

    private int count = 0;

    public MyArrayBlockingQueue(){
        arr = new Object[16];
        size = 16;
        lock = new ReentrantLock();
        notEmpty = lock.newCondition();
        notFull = lock.newCondition();
    }

    public void put(Object o){
        ReentrantLock lock = this.lock;
        lock.lock();
        try {
            while (count == size){
                // 满了
                notEmpty.signal();
                notFull.await();
            }
            arr[count] = o;
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            notEmpty.signal();
            lock.unlock();
        }
    }



    public Object take(){
        lock.lock();
        try {
            while (count==0){
                notFull.signal();
                notEmpty.await();
            }
            count--;
            return arr[count];
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } finally {
            notFull.signal();
            lock.unlock();
        }
    }
}


class TestMyBlockingQueue{

    public static void main(String[] args) {
        MyArrayBlockingQueue queue = new MyArrayBlockingQueue();
//        new Thread(()->{
//            for (int i = 0;i<20;i++){
//                queue.put(i);
//            }
//        },"A").start();
        new Thread(()->{
            for (int i=0;i<20;i++){
                System.out.println(queue.take());
            }
        },"B").start();
    }
}